<!-- src/components/BorrowBookDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    title="借阅图书"
    width="500px"
    @close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="图书信息">
        <el-descriptions :column="1" size="small" border>
          <el-descriptions-item label="书名">{{ book.title }}</el-descriptions-item>
          <el-descriptions-item label="作者">{{ book.author }}</el-descriptions-item>
          <el-descriptions-item label="ISBN">{{ book.isbn }}</el-descriptions-item>
        </el-descriptions>
      </el-form-item>

      <el-form-item label="借阅人姓名" prop="borrowerName">
        <el-input v-model="form.borrowerName" placeholder="请输入借阅人姓名" />
      </el-form-item>

      <el-form-item label="联系电话" prop="borrowerPhone">
        <el-input v-model="form.borrowerPhone" placeholder="请输入联系电话" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确认借阅
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, defineExpose } from 'vue'

export default {
  name: 'BorrowBookDialog',
  props: {
    book: {
      type: Object,
      required: true
    }
  },
  setup(props, { emit }) {
    const visible = ref(false)
    const submitting = ref(false)
    const formRef = ref(null)

    const form = reactive({
      borrowerName: '',
      borrowerPhone: ''
    })

    const rules = {
      borrowerName: [
        { required: true, message: '请输入借阅人姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
      ],
      borrowerPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ]
    }

    const show = () => {
      visible.value = true
      form.borrowerName = ''
      form.borrowerPhone = ''
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }

    const handleClose = () => {
      visible.value = false
    }

    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        submitting.value = true

        emit('confirm', {
          bookId: props.book.id,
          borrowerName: form.borrowerName,
          borrowerPhone: form.borrowerPhone
        })
      } catch (error) {
        console.error('表单验证失败:', error)
      } finally {
        submitting.value = false
      }
    }

    defineExpose({
      show
    })

    return {
      visible,
      submitting,
      formRef,
      form,
      rules,
      show,
      handleClose,
      handleSubmit
    }
  }
}
</script>